﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kovan.Model.Entity.Config;
using Kovan.BLL.Config;
using Kovan.Model.Parameter.Config;
using System.IO;
using Kovan.Library.Drawing;
using Kovan.Library.Configuration;

namespace Kovan.UI.Areas.Manage.Controllers
{
    public class PicGroupController : ManageControllerBase
    {
        //
        // GET: /Manage/PicGroup/

        public ActionResult Index(PPicGroup param)
        {
            if (!(param.PageSize > 0))
            {
                param.PageSize = 20;
            }
            if (!(param.PageIndex > 0))
            {
                param.PageIndex = 1;
            }
            var items = BPicGroup.GetInstances().GetList(param);
            ViewBag.Param = param;
            return View("index", items);
        }

        /// <summary>
        /// 删除相册
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ContentResult Delete(string ids)
        {
            var statuscode = string.Empty;
            List<string> idss = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var result = BPicGroup.GetInstances().BatchDelete(idss);
            if (result > 0)
            {
                statuscode = GetSucceedCode("操作成功", "picgroup_manage", Url.Content("~/Manage/PicGroup"), "相册管理");
            }
            return Content(statuscode);
        }

        /// <summary>
        /// 删除相片
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="pgid"></param>
        /// <returns></returns>
        public ContentResult DeletePicture(string ids, int? pgid)
        {
            string title = string.Empty;
            string pgUkey = string.Empty;
            if (pgid.HasValue && pgid.Value > 0)
            {
                var model = BPicGroup.GetInstances().GetModel(pgid.Value);
                if (model != null)
                {
                    title = model.name;
                    pgUkey = model.ukey;
                }
            }
            var statuscode = string.Empty;
            List<string> idss = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            //var result = BPicGroup.GetInstances().BatchDelete(idss);
            var result = BPicture.GetInstances().BatchDelete(idss, pgUkey);
            if (result > 0)
            {
                statuscode = GetSucceedCode("操作成功", "picgroup_upload", Url.Content("~/Manage/PicGroup/Picture?picgroupId=" + pgid), title);
            }
            return Content(statuscode);
        }

        /// <summary>
        /// 弹出页面 编辑相册
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetOperate(int? id)
        {
            tb_picgroup model = new tb_picgroup();
            if (id.HasValue)
            {
                model = BPicGroup.GetInstances().GetModel(id.Value);
            }
            return View("OperateDialog", model);
        }

        /// <summary>
        /// 弹出页面 编辑相片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetPictureOperate(int? id)
        {
            tb_picture model = new tb_picture();
            if (id.HasValue)
            {
                model = BPicture.GetInstances().GetModel(id.Value);
            }
            return View("PictureOperateDialog", model);
        }

        /// <summary>
        /// 相册（保存 或 更新 ）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SavePicGroup(tb_picgroup model)
        {
            int result = 0;
            string statuscode = string.Empty;
            if (model.picgroup_id.HasValue)
            {
                var model1 = BPicGroup.GetInstances().GetModel(model.picgroup_id.Value);
                model1.name = model.name;
                if (!string.IsNullOrEmpty(model.description))
                {
                    model1.description = model.description;
                }
                model1.is_index = model.is_index;
                model1.is_view = model.is_view;
                model1.sort_order = model.sort_order;
                model1.last_modify_user = 0;

                result = BPicGroup.GetInstances().Update(model1);
            }
            else
            {
                model.create_date = DateTime.Now;
                model.create_user = 0;
                model.create_usernane = "";
                model.last_modify_date = model.create_date;
                model.last_modify_user = 0;
                model.ukey = Guid.NewGuid().ToString("N");
                result = BPicGroup.GetInstances().Add(model);
            }

            if (result > 0)
            {
                //成功
                statuscode = GetSucceedCode("保存成功", "picgroup_manage", Url.Content("~/Manage/PicGroup"), "友情链接");
            }
            else
            {
                //失败
                statuscode = GetFailCode("保存失败", "", "", "");
            }
            return Content(statuscode);
        }

        /// <summary>
        /// 更新相片信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SavePicture(tb_picture model)
        {
            int result = 0;
            string statuscode = string.Empty;
            string title = string.Empty;
            if (model.picture_id.HasValue && model.picgroup_id.HasValue)
            {
                var picgroupModel = BPicGroup.GetInstances().GetModel(model.picgroup_id.Value);
                title = picgroupModel.name;
                var model1 = BPicture.GetInstances().GetModel(model.picture_id.Value);
                model1.title = model.title;
                model1.keyword = model.keyword;
                model1.description = model.description;
                model1.is_cover = model.is_cover;
                model1.is_view = model.is_view;
                result = BPicture.GetInstances().Update(model1);
            }

            if (result > 0)
            {
                //成功
                statuscode = GetSucceedCode("保存成功", "picgroup_upload", Url.Content("~/Manage/PicGroup/Picture?picgroupId=" + model.picgroup_id), title);
            }
            else
            {
                //失败
                statuscode = GetFailCode("保存失败", "", "", "");
            }
            return Content(statuscode);
        }

        /// <summary>
        /// 相片列表显示页面
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Picture(PPicture param)
        {
            if (!(param.PageSize > 0))
            {
                param.PageSize = 15;
            }
            if (!(param.PageIndex > 0))
            {
                param.PageIndex = 1;
            }
            var item = new tb_picgroup();
            if (param.picgroupId.HasValue)
            {
                item = BPicGroup.GetInstances().GetModel(param.picgroupId.Value);
                if (item != null)
                {
                    var pictures = BPicture.GetInstances().GetList(param);
                    ViewBag.pictures = pictures;
                }
            }
            ViewBag.param = param;
            return View("PictureList", item);
        }

        /// <summary>
        /// 上传组件 弹出页面
        /// </summary>
        /// <param name="pgid"></param>
        /// <returns></returns>
        public ActionResult GetUpload(int? pgid)
        {
            var model = new tb_picgroup();
            if (pgid.HasValue && pgid.Value > 0)
            {
                model = BPicGroup.GetInstances().GetModel(pgid.Value);
            }
            ViewBag.PicGroup = model;
            return View("Upload");
        }

        /// <summary>
        /// 图片上传处理
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="PicGroupUkey"></param>
        /// <param name="PicGroupID"></param>
        /// <returns></returns>
        public JsonResult UploadPic(HttpPostedFileBase fileData, string PicGroupUkey, int? PicGroupID)
        {
            if (fileData != null)
            {
                try
                {
                    var PicPath = ConfigurationUtility.AppSettings<string>("PicPath", "content/Uploads/Pic/");
                    // 文件上传后的保存路径
                    string filePath = Server.MapPath("~/" + PicPath + (string.IsNullOrEmpty(PicGroupUkey) ? "" : PicGroupUkey + "/"));
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileTitle = Path.GetFileNameWithoutExtension(fileName);//文件名称，不包括扩展名
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = Guid.NewGuid().ToString() + fileExtension; // 保存文件名称
                    string smallSaveName = Guid.NewGuid().ToString() + "_small" + fileExtension; // 保存文件名称
                    var path = filePath + saveName;
                    var smallPath = filePath + smallSaveName;

                    fileData.SaveAs(path);
                    //生成缩略图
                    ImageUtility.ResizeImageToAFixedSize(path, smallPath, 250, 200, ImageUtility.ScaleMode.W);

                    //插入相片信息到数据库
                    tb_picture model = new tb_picture();
                    model.create_date = DateTime.Now;
                    model.create_user = 0;
                    model.create_username = "";
                    model.description = "";
                    model.is_cover = 0;
                    model.is_view = 1;
                    model.picgroup_id = PicGroupID;
                    model.path = saveName;
                    model.small_path = smallSaveName;
                    model.title = fileTitle;
                    BPicture.GetInstances().Add(model);

                    return Json(new { Success = true, FileName = fileName, SaveName = saveName });
                }
                catch (Exception ex)
                {
                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {

                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);
            }
        }

    }
}
